<?php

/*
 * To change this template, choose Tools | Templates
* and open the template in the editor.
*/

class HT_Model_administrator_models_userrequest extends Zend_Db_Table {//ten class fai viet hoa

	protected $_db;

	public function __construct() {
		$this->_name = "user_request";
		$this->_db = Zend_Registry::get('dbMain');
		parent::init();
	}
	
	public function addData($data){
		$ipRequest = $data['ip_request'];
		$totalRequest = $this->_countIpRequest($ipRequest);
		if($totalRequest < 5){
			$this->insert($data);
			return $this->getMaxId();
		}else{
			return "-1";
		}
	}
	
	private function _countIpRequest($ipRequest){
		$sql = "SELECT COUNT(request_id) FROM user_request WHERE ip_request = ? AND date(request_date) = date('".date('Y-m-d')."')";
		return  $this->_db->fetchOne($sql,array($ipRequest));
	}
	
	public function getMaxId(){
		$sql = "SELECT MAX(request_id) FROM user_request";
		return  (int)$this->_db->fetchOne($sql);
	}
	public function getUserrequest($typeId,$filter = array()) {
		$sql = " SELECT * FROM user_request WHERE request_id= ".(int)$typeId;
		return $this->_db->fetchRow($sql);
	}
	public function getListUserrequest_nb($filter = array()) {
		$sqlPlus = $this->getListUserrequest_sqlPlus($filter);
		$sql = "SELECT COUNT(request_id)
		FROM user_request
		WHERE 1=1 $sqlPlus";
		return $this->_db->fetchOne($sql);
	}
	public function getListUserrequest($start=0,$size = 10,$filter = array()) {
		$sqlPlus = $this->getListUserrequest_sqlPlus($filter);
		$sql = "SELECT *
		FROM user_request
		WHERE 1=1 $sqlPlus ORDER BY subject LIMIT $start,$size";
		return $this->_db->fetchAll($sql);
	}
	
	private function getListUserrequest_sqlPlus($filter){
		$sqlPlus = null;
		$keyword = addslashes(trim(@$filter['keyword']));
		if($keyword){
			$sqlPlus .= " AND (subject LIKE '%$keyword%' OR `content` LIKE '%$keyword%') ";
		}
		return $sqlPlus;
	}	
}

?>
